package zplh.com.commonlibrary.utils;

import android.annotation.SuppressLint;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import zplh.com.commonlibrary.LibraryManager;
import zplh.com.resourcelibrary.constants.SystemConstant;

/**
 * 脚本工具类
 * Created by yong hao zeng on 2018/6/29.
 */
public class ScriptUtils {


    //初始化内置脚本
    public static  void init(final InitCallback initCallback){
        boolean isNeedInstall ;

        isNeedInstall = !isNewScript(getScriptPackageName("BaseScript.apk"), SystemConstant.BASE_SCRIPT_VERSION);
            //检查脚本是否安装
        if (isNeedInstall){
            //未安装
            FileUtils.getInstance(LibraryManager.getContext())
                    .copyAssetsToSD("BaseScript.apk","/scripts" )
                    .setFileOperateCallback(new FileUtils.FileOperateCallback() {
                        @SuppressLint("CheckResult")
                        @Override
                        public void onSuccess() {
                            Observable.create((ObservableEmitter<Boolean> emitter) -> {
                                ScriptUtils.uninstallScript(getScriptPackageName("BaseScript.apk"));
                                int i = installScript("BaseScript.apk");
                                emitter.onNext(i == 0);
                            }).subscribeOn(Schedulers.newThread())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(b -> {
                                      if (b)
                                        initCallback.onSuccess();
                                         else initCallback.onError("安装基础脚本失败");
                                    });
                        }
                        @Override
                        public void onFailed(String error) {
                            initCallback.onError(error);
                        }
                    });
        }else {
            initCallback.onSuccess();
        }
    }


    public static int applyScript(String scriptPackageName,String methodName,String data){
        String command;
        if (TextUtils.isEmpty(data)){
           command = "am instrument  --user 0 -w -r -e debug false -e class "+scriptPackageName+"."+methodName+" "+scriptPackageName+".test/android.support.test.runner.AndroidJUnitRunner";
        }else {
            command = "am instrument  --user 0 -w -r -e param " + data +" -e debug false -e class "+scriptPackageName+"."+methodName+" "+scriptPackageName +".test/android.support.test.runner.AndroidJUnitRunner";
        }
        CommandResult commandResult = ShellUtils.execCommand(command, true);
        if (commandResult.result == 0)
            return 0;
        else return -1;

    }


    //安装脚本
    //return 0 安装成功 其余失败
    public static int installScript(String fileName) {
        CommandResult commandResult = ShellUtils.execCommand("pm install -t -r -g -d " + FileUtils.getScriptPath(fileName), true);
        if (commandResult.result == 0)
            return 0;
        else return -1;
    }


    //安装脚本
    //return 0 安装成功 其余失败
    public static int installScript(File file) {
        CommandResult commandResult = ShellUtils.execCommand("pm install -t -r -g -d " + file.getAbsolutePath(), true);
        if (commandResult.result == 0)
            return 0;
        else
            ToastUtils.showToastError(LibraryManager.getContext(),commandResult.errorMsg);

            return -1;
    }


    /**
     * 通过文件名获取包名
     * @param scriptName 当前脚本文件名
     * @return
     */
    public static String getScriptPackageName(String scriptName){
        String scriptPath = FileUtils.getScriptPath(scriptName);
        if (TextUtils.isEmpty(scriptPath)) return "";
        PackageManager packageManager = LibraryManager.getContext().getPackageManager();
        PackageInfo packageArchiveInfo = packageManager.getPackageArchiveInfo(scriptPath, PackageManager.GET_ACTIVITIES);
        if (packageArchiveInfo == null) return "";
        return packageArchiveInfo.packageName;
    }


    //获取没有安装的apk包的版本号
    public static String getApkVersionCode(String scriptName){
        String scriptPath = FileUtils.getScriptPath(scriptName);
        if (TextUtils.isEmpty(scriptPath)) return "";
        PackageManager packageManager = LibraryManager.getContext().getPackageManager();
        PackageInfo packageArchiveInfo = packageManager.getPackageArchiveInfo(scriptPath, PackageManager.GET_ACTIVITIES);
        if (packageArchiveInfo == null) return "";
        return packageArchiveInfo.versionCode+"";
    }


    /**
     *     //某个脚本是否是最新的
     * @param scriptPackageName 脚本包名
     * @param scriptVersion 最新的脚本版本号
     * @return 除非安装过脚本 并且是最新的 否则全部返回false
     */
    public static boolean isNewScript(String scriptPackageName,int scriptVersion){
        if (TextUtils.isEmpty(scriptPackageName)) {
            try {
                throw new Exception("没有安装此脚本");
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        PackageManager packageManager = LibraryManager.getContext().getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(scriptPackageName, PackageManager.GET_ACTIVITIES);
            if (packageInfo == null) return false;
            int oldVersion =  packageInfo.versionCode;
            if (oldVersion<scriptVersion){
                return false;
            }else {
                return true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }

    }



    public static void uninstallScript(String scriptPackageName){
        ShellUtils.execCommand("pm uninstall "+scriptPackageName+".test", true);

    }



    /**
     *     //某个脚本版本是否是一致的
     * @param scriptPackageName 脚本包名
     * @param scriptVersion 最新的脚本版本号
     * @return 除非安装过脚本 并且是跟参数版本一致 否则全部返回false
     */
    public static boolean checkScript(String scriptPackageName,int scriptVersion){

        if (TextUtils.isEmpty(scriptPackageName)) {
            try {
                throw new Exception("没有安装此脚本");
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        PackageManager packageManager = LibraryManager.getContext().getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(scriptPackageName, PackageManager.GET_ACTIVITIES);
            if (packageInfo == null) return false;
            int oldVersion =  packageInfo.versionCode;
            if (oldVersion == scriptVersion){
                return false;
            }else {
                return true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }


    //是否安装过某个脚本
    public static boolean isInstallScript(String scriptPackageName){
        CommandResult commandResult = ShellUtils.execCommand("pm path " + scriptPackageName, true);
        return !TextUtils.isEmpty(commandResult.successMsg);
    }

    public static void stop(String packageName) {
        ShellUtils.execCommand("am force-stop "+packageName, true);

    }


    public interface InitCallback{
       void onSuccess();
       void onError(String error);
    }


}
